import type { Directive, DirectiveBinding } from 'vue'

interface ElType extends HTMLElement {
  __handleClick__: () => void
}

const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null
  return function (this: any, ...args: any[]) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

export default {
  mounted(el: ElType, binding: DirectiveBinding) {
    if (typeof binding.value !== 'function') {
      throw new Error('v-debounce value must be a function')
    }
    
    const delay = Number(binding.arg) || 300 // 默认300ms
    el.__handleClick__ = debounce(binding.value, delay)
    el.addEventListener('click', el.__handleClick__)
  },
  
  beforeUnmount(el: ElType) {
    el.removeEventListener('click', el.__handleClick__)
  }
} as Directive 